package com.github.catvod.spider;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Filter;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.net.OkResult;
import com.github.catvod.utils.AESEncryption;
import com.github.catvod.utils.AgeUtil;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.Util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author fs
 * AGE动漫:https://m.agedm.org/
 */
public class AGE extends Spider {
    private static String siteUrl="https://m.agedm.org/";
    private static String filterUrl="https://cdn.aiqingyu1314.com/agem/js/chunk-4e6f68d4.ee133aed.js";

    // 请求接口API
    private static  String API_URL = "https://api.agedm.org/v2/";

    private String Search_api = API_URL + "search";
    private String detail_api = API_URL + "detail/";

    private Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        header.put("referer", "https://m.agedm.org/");
        return header;
    }

    @Override
    public String homeContent(boolean filter) throws Exception {
        List<Class> classes = new ArrayList<>();
        LinkedHashMap<String, List<Filter>> filters = new LinkedHashMap<>();
        List<String> typeIds = Arrays.asList("recommend", "catalog", "update");
        List<String> typeNames = Arrays.asList("推荐", "目录", "最近更新");
        for (int i = 0; i < typeIds.size(); i++) classes.add(new Class(typeIds.get(i), typeNames.get(i)));
        // 进行获取过滤列表
        String result = OkHttp.string(filterUrl, getHeader());
        Pattern pattern = Pattern.compile("filters:(.*)\\},TmpLabels");
        Matcher matcher = pattern.matcher(result);
        String filterData = matcher.find() ? matcher.group(1) : "";
        JSONArray jsonArray = new JSONArray(filterData);
        List<Filter> array = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            List<Filter.Value> values = new ArrayList<>();
            JSONObject bar = jsonArray.getJSONObject(i);
            String key = bar.getString("name");
            String name = bar.getString("label");
            JSONArray data_arr = bar.getJSONArray("data");
            for (int j = 0; j < data_arr.length(); j++) {
                JSONObject data = data_arr.getJSONObject(j);
                values.add(new Filter.Value(data.getString("text"), data.getString("value")));
            }
            array.add(new Filter(key, name, values));
        }
        filters.put("catalog", array);
        return Result.string(classes, new ArrayList<>(), filters);
    }

    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        if (extend.get("genre") == null) extend.put("genre", "all");
        if (extend.get("label") == null) extend.put("label", "all");
        if (extend.get("letter") == null) extend.put("letter", "all");
        if (extend.get("order") == null) extend.put("order", "time");
        if (extend.get("region") == null) extend.put("region", "all");
        if (extend.get("resource") == null) extend.put("resource", "all");
        if (extend.get("season") == null) extend.put("season", "all");
        if (extend.get("status") == null) extend.put("status", "all");
        if (extend.get("year") == null) extend.put("year", "all");
        // 进行获取类型
        String genre = extend.get("genre");
        String label = extend.get("label");
        String letter = extend.get("letter");
        String order = extend.get("order");
        String region = extend.get("region");
        String resource = extend.get("resource");
        String season = extend.get("season");
        String status = extend.get("status");
        String year = extend.get("year");
        List<Vod> vodList = new ArrayList<>();
        if (tid.equals("recommend")){
            JSONObject result = Json.parseJson(OkHttp.string(API_URL + "recommend", getHeader()));
            // 获取视频列表
            JSONArray result_arr = result.getJSONArray("videos");
            for (int i = 0; i < result_arr.length(); i++) {
                JSONObject video = result_arr.getJSONObject(i);
                vodList.add(new Vod(video.getString("AID"), video.getString("Title"), video.getString("PicSmall"), video.getString("NewTitle")));
            }
            return Result.get().vod(vodList).page(1, 1, 1, result.getInt("total")).string();
        }else if (tid.equals("update")){
            HashMap<String, String> params = new HashMap<>();
            params.put("page", pg);
            params.put("size", "30");
            JSONObject result = Json.parseJson(OkHttp.string(API_URL + "update",params, getHeader()));
            // 获取视频列表
            JSONArray result_arr = result.getJSONArray("videos");
            for (int i = 0; i < result_arr.length(); i++) {
                JSONObject video = result_arr.getJSONObject(i);
                vodList.add(new Vod(video.getString("AID"), video.getString("Title"), video.getString("PicSmall"),video.getString("NewTitle")));
            }
            return Result.get().vod(vodList).page(Integer.parseInt(pg),Integer.parseInt(pg)+1, 1, result.getInt("total")).string();
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("genre", genre);
        params.put("label", label);
        params.put("letter", letter);
        params.put("order", order);
        params.put("region", region);
        params.put("resource", resource);
        params.put("season", season);
        params.put("status", status);
        params.put("year", year);
        params.put("page", pg);
        params.put("size", "10");
        JSONObject result = Json.parseJson(OkHttp.string(API_URL + "catalog", params, getHeader()));
        // 获取视频列表
        JSONArray result_arr = result.getJSONArray("videos");
        for (int i = 0; i < result_arr.length(); i++) {
            JSONObject video = result_arr.getJSONObject(i);
            String cover = video.getString("cover");
            String id = video.getString("id");
            String name = video.getString("name");
            String intro = video.getString("intro");
            String remark = video.getString("uptodate");
            String tags = video.getString("tags");
            String writer = video.getString("writer");
            Vod vod = new Vod();
            vod.setVodId(id);
            vod.setVodPic(cover);
            vod.setVodName(name);
            vod.setVodRemarks(remark);
            vod.setVodPic(cover);
            vod.setVodActor(writer);
            vod.setVodDirector(tags);
            vod.setVodContent(intro);
            vod.setVodTag(tags);
            vodList.add(vod);
        }
        return Result.get().vod(vodList).page(Integer.parseInt(pg),Integer.parseInt(pg)+1, 1, result.getInt("total")).string();
    }

    @Override
    public String detailContent(List<String> ids) throws Exception {
        String result = OkHttp.string(detail_api + ids.get(0), getHeader());
        JSONObject result_json = new JSONObject(result);
        JSONObject playerLabelObj = result_json.getJSONObject("player_label_arr");
        // 播放解析地址
        JSONObject player_jx = result_json.getJSONObject("player_jx");
        // VIP解析地址
        String playerVip = result_json.getString("player_vip");
        JSONObject video = result_json.getJSONObject("video");
        String area = video.getString("area");
        String cover = video.getString("cover");
        String name = video.getString("name");
        String intro = video.getString("intro");
        String status = video.getString("status");
        String year = video.getString("year");
        String tags = video.getString("tags");
        JSONObject playlists = video.getJSONObject("playlists");
        ArrayList<String> fromLink = new ArrayList<>();
        ArrayList<String> player = new ArrayList<>();
        for (int i = 0; i < playlists.length(); i++) {
            // 获取键名
            String key = Objects.requireNonNull(playlists.names()).get(i).toString();
            // 根据键进行获取名字
            String keyname = playerLabelObj.getString(key);
            fromLink.add(keyname);
            JSONArray play_arr = playlists.getJSONArray(key);
            StringBuilder url= new StringBuilder();
            for (int j = 0; j < play_arr.length(); j++) {
                JSONArray play_info =  play_arr.getJSONArray(j);
                String playName = play_info.getString(0);
                String playUrl = play_info.getString(1);
                // 进行判断是否是需要进行vip解析
                if (playerVip.contains(key)) {
                    // 获取VIP解析
                    String vip = player_jx.getString("vip");
                    url.append(playName).append("$").append(vip).append(playUrl).append("#");
                }else {
                    String zj = player_jx.getString("zj");
                    url.append(playName).append("$").append(zj).append(playUrl).append("#");
                }
            }
            // 进行去除最后一个
            url = new StringBuilder(url.substring(0, url.length() - 1));
            player.add(url.toString());
        }
        Vod vod = new Vod();
        vod.setVodId(ids.get(0));
        vod.setVodPic(cover);
        vod.setVodName(name);
        vod.setVodRemarks(status);
        vod.setVodYear(year);
        vod.setVodArea(area);
        vod.setVodDirector(tags);
        vod.setVodContent(intro);
        vod.setVodPlayFrom(TextUtils.join("$$$", fromLink));
        vod.setVodPlayUrl(TextUtils.join("$$$", player));
        return Result.string(vod);
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("query", key);
        params.put("page", "1");
        OkResult okResult = OkHttp.get(Search_api, params, getHeader());
        JSONObject jsonObject = new JSONObject(okResult.getBody()).getJSONObject("data");
        JSONArray video_arr = jsonObject.getJSONArray("videos");
        List<Vod> vodList = new ArrayList<>();
        for (int i = 0; i < video_arr.length(); i++) {
            JSONObject video = video_arr.getJSONObject(i);
            Vod vod = new Vod();
            vod.setVodId(video.getString("id"));
            vod.setVodName(video.getString("name"));
            vod.setVodPic(video.getString("cover"));
            vod.setVodRemarks(video.getString("uptodate"));
            vodList.add(vod);
        }
        return Result.string(vodList);
    }

    @SuppressLint("NewApi")
    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        String string = OkHttp.string(id, getHeader());
        Pattern vurl_pattern = Pattern.compile("var Vurl = ['\"](.+?)['\"];");
        Pattern time_pattern = Pattern.compile("var Time = ['\"](.+?)['\"];");
        Pattern version_pattern = Pattern.compile("var Version = ['\"](.+?)['\"];");

        Matcher vurl_matter = vurl_pattern.matcher(string);
        Matcher time_matter = time_pattern.matcher(string);
        Matcher version_matter = version_pattern.matcher(string);
        String vurl = vurl_matter.find() ? vurl_matter.group(1) : "";
        // 进行判断vuel是否被加密
        if(!vurl.startsWith("https://") || vurl.isBlank()){
            String time = time_matter.find() ? time_matter.group(1) : "";
            String version = version_matter.find() ? version_matter.group(1) : "";
            String host = Util.getHost(id);
            // 进行获取uuid
            String uuid = AgeUtil.generateUUID();
            JSONObject param = new JSONObject();
            param.put("url", vurl);
            param.put("wap", "0");
            param.put("ios", "0");
            param.put("host", host);
            param.put("referer", "aHR0cHM6Ly93d3cuYWdlZG0ub3JnLw=="); // Base64编码的字符串
            param.put("time", time);
            String aa = AgeUtil.hxm_encrypt(param.toString()).toUpperCase();
            String api="https://"+host+":8443/vip/Api.php";
            Map<String,String> apiParams = new HashMap<>();
            System.out.println(aa);
            apiParams.put("Params", aa);
            String sign=AgeUtil.hxm_encrypt(host + " | " + uuid + " | " + time + " | " + version + " | " + aa).toUpperCase();
            String result = Util.postBody(api, apiParams, getApiHeader(uuid, time, version, sign));
            JSONObject result_json = new JSONObject(result);
            System.out.println(result_json);
            // 进行匹配id
            List<String> ids = AgeUtil.extractIds(string, 2);
            String getId =  ids.stream()
                    .map(x -> x.replace("\"", "").replace("id=", "").replace("viewport", ""))
                    .collect(Collectors.joining(""));
            String code = result_json.getString("Code").equals("10") ? getId : "";
            String s = result_json.getString("Code") + code + result_json.getString("Appkey") + result_json.getString("Version");
            String s1 = AESEncryption.aesCbcDecrypt(result_json.getString("Data"), Util.MD5(s, "UTF-8"));
            System.out.println(s1);
            // 进行解析请求
            JSONObject responseJson = new JSONObject(s1);
            String url = responseJson.getString("url");
            // 进行解密
            String playUrl = AgeUtil.hxm_decrypt(url);
            playUrl = Util.decodeURIComponent(playUrl);
            return Result.get().url(playUrl).header(getHeader()).string();
        }
        return Result.get().url(vurl).header(getHeader()).string();
    }

    private Map<String, String> getApiHeader(String uuid, String time,String version,String sign) {
        Map<String, String> header = new HashMap<>();
        header.put("x-requested-with", "XMLHttpRequest");
        header.put("Accept", "application/json");
        header.put("video-parse-uuid", uuid);
        header.put("video-parse-time", time);
        header.put("video-parse-version", version);
        header.put("video-parse-sign",sign);
        return header;
    }
}
